//
//  YFOauthViewController.swift
//  微博
//
//  Created by 余仿 on 16/4/9.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

import SVProgressHUD
class YFOauthViewController: UIViewController,UIWebViewDelegate {


    var webView:UIWebView?

    override func loadView() {

        webView = UIWebView()

        webView?.delegate = self

        view = webView

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "测试账户", target: self, action: "autoLogIn")

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")

        //加载授权页
        loadAuthorizationPage()
    }


    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        SVProgressHUD.dismiss()
    }

    func autoLogIn(){
        webView?.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 18767879586,document.getElementById('passwd').value = 'yufang93@mzj'")
    }

    func close(){

        dismissViewControllerAnimated(true, completion: nil)

    }

    //MARK:加载授权页
    func loadAuthorizationPage(){

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=350157411&redirect_uri=https://movie.douban.com/"

        let url = NSURL(string: urlString)

        let request = NSURLRequest(URL: url!)

        webView?.loadRequest(request)
    }


}


//MARK:webView的代理方法
extension YFOauthViewController{

        func webViewDidStartLoad(webView: UIWebView) {
    
            SVProgressHUD .show()
        }
    
        func webViewDidFinishLoad(webView: UIWebView) {
    
            SVProgressHUD.dismiss()
    
        }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let urlString = (request.URL?.absoluteString)!


        if urlString.containsString("code="){


            let ocString = urlString as NSString

            let range = ocString.localizedStandardRangeOfString("code=")

            let code = ocString.substringFromIndex(range.location + range.length)

            //根据获得的code请求access_token
            YFViewModel.sharedViewModels.loadAccessToken(code, accessTokenFinished: { (result) -> () in

                //销毁当前控制器
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //跳转欢迎控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(YFSwitchRootController, object: nil)
                })
            })
            
            return false
        }
        
        return true
    }
    
}